"""知识点删除相关视图

此模块包含用于删除知识点的视图函数和相关功能。
"""
import logging
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_http_methods
from core.models import KnowledgePoint, TeacherSubjectAssignment
from core.utils import log_operation

logger = logging.getLogger(__name__)

def _has_subject_permission(request: HttpRequest, subject_id: int) -> bool:
    """检查用户是否有权限操作指定学科

    Args:
        request: HTTP请求对象
        subject_id: 学科ID

    Returns:
        bool: 用户是否有权限
    """
    return TeacherSubjectAssignment.objects.filter(
        teacher=request.user,
        subject_id=subject_id
    ).exists()


@login_required
def knowledge_point_delete_view(request: HttpRequest, pk: int) -> HttpResponse:
    """删除知识点（页面版）

    该视图函数显示删除确认页面，并处理知识点的删除操作。
    验证用户是否有权限操作此知识点所属的学科。

    Args:
        request: HTTP请求对象
        pk: 知识点的主键ID

    Returns:
        HttpResponse: 渲染的删除确认页面或重定向到知识点列表
    """
    knowledge_point = get_object_or_404(KnowledgePoint, pk=pk)
    chapter = knowledge_point.chapter

    # 验证用户是否有权限操作此知识点所属的学科
    if not _has_subject_permission(request, chapter.subject_id):
        return render(request, 'knowledge_point/permission_denied.html', status=403)

    if request.method == 'POST':
        with transaction.atomic():
            kp_name = knowledge_point.name
            knowledge_point.delete()
        log_operation(
            user=request.user,
            operation_type='delete',
            content_type='KnowledgePoint',
            object_id=pk,
            object_name=kp_name,
            request=request,
            details=f'删除知识点: {kp_name}'
        )
        return redirect('core:knowledge_point_list', chapter_id=chapter.id)

    return render(request, 'knowledge_point/knowledge_point_confirm_delete.html', {
        'knowledge_point': knowledge_point,
        'chapter': chapter
    })


@require_http_methods(["POST"])
@login_required
def knowledge_point_ajax_delete(request: HttpRequest) -> JsonResponse:
    """删除知识点（AJAX版）

    该视图函数处理AJAX请求，用于异步删除知识点。
    验证用户是否有权限操作此知识点所属的学科，并返回JSON格式的响应。

    Args:
        request: HTTP请求对象，包含要删除的知识点ID

    Returns:
        JsonResponse: 包含操作结果的JSON响应
    """
    try:
        kp_id = request.POST.get('id')

        if not kp_id:
            return JsonResponse({'success': False, 'message': '知识点ID为必填项'})

        # 获取知识点并验证权限
        try:
            knowledge_point = KnowledgePoint.objects.get(id=kp_id)
        except KnowledgePoint.DoesNotExist:
            return JsonResponse({'success': False, 'message': '知识点不存在'})

        # 验证用户是否有权限操作此知识点所属的学科
        if not _has_subject_permission(request, knowledge_point.chapter.subject_id):
            return JsonResponse({'success': False, 'message': '无权限删除此知识点'})

        with transaction.atomic():
            kp_name = knowledge_point.name
            knowledge_point.delete()

        log_operation(
            user=request.user,
            operation_type='delete',
            content_type='KnowledgePoint',
            object_id=kp_id,
            object_name=kp_name,
            request=request,
            details=f'删除知识点: {kp_name}'
        )
        return JsonResponse({
            'success': True,
            'message': '知识点删除成功'
        })

    except Exception as e:
        logger.error(f"删除知识点失败: {str(e)}", exc_info=True)
        return JsonResponse({'success': False, 'message': f'删除失败: {str(e)}'})